package com.rongchuang.service;

import com.querydsl.jpa.impl.JPAQueryFactory;
import com.rongchuang.dto.RoleDTO;
import com.rongchuang.entity.Role;
import com.rongchuang.entity.UserRole;
import com.rongchuang.repository.RoleRepository;
import com.rongchuang.repository.UserRoleRepository;
import com.rongchuang.util.ConverterUtil;
import com.rongchuang.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserRoleService {

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private JPAQueryFactory queryFactory;

    @Transactional(rollbackFor = Exception.class)
    public void addRole(Long userId, List<Long> roleIds) {
        // 删除当前用户角色
        userRoleRepository.deleteByUserId(userId);

        // 新增用户当前角色
        List<UserRole> userRoles = roleIds.stream().map(e -> {
            UserRole userRole = new UserRole();
            userRole.setRoleId(e);
            userRole.setUserId(userId);
            userRole.setCreateTime(DateUtils.getCurrentTime());
            userRole.setUpdateTime(DateUtils.getCurrentTime());
            return userRole;
        }).collect(Collectors.toList());
        userRoleRepository.saveAll(userRoles);
    }

    /**
     * 获取用户关联角色ids
     * @param userId 用户id
     * @return 角色ids
     */
    public List<RoleDTO> findRoleIdByUserId(Long userId) {
        // 获取用户关联角色
        List<UserRole> userRoles = userRoleRepository.findByUserId(userId);
        List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).distinct().collect(Collectors.toList());
        // 获取用户角色信息
        List<Role> roles = roleRepository.findAllById(roleIds);
        return ConverterUtil.convertToList(roles, RoleDTO.class);
    }
}
